import React, { useEffect, useState } from 'react';
import { Form, Input, Button, Card, message, Spin, Alert, Result, Select } from 'antd';
import { UserOutlined, LockOutlined, IdcardOutlined, TeamOutlined } from '@ant-design/icons';
import { Link, useNavigate } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import { registerStudent, clearError } from '../../store/slices/authSlice';
import { studentAPI } from '../../services/api';
import './index.scss';

const { Option } = Select;

const Register = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { loading, error, isAuthenticated } = useSelector((state) => state.auth);
  const [registerSuccess, setRegisterSuccess] = useState(false);
  const [classList, setClassList] = useState([]);
  const [classLoading, setClassLoading] = useState(false);

  useEffect(() => {
    // 如果已经登录，重定向到首页
    if (isAuthenticated) {
      navigate('/dashboard');
    }
  }, [isAuthenticated, navigate]);

  useEffect(() => {
    // 处理错误信息
    if (error) {
      message.error(error);
      dispatch(clearError());
    }
  }, [error, dispatch]);

  // 获取班级列表
  useEffect(() => {
    const fetchClassList = async () => {
      setClassLoading(true);
      try {
        const response = await studentAPI.getClassList();
        if (response.data && response.data.code === 2000) {
          setClassList(response.data.data.classes || []);
        } else {
          message.error('获取班级列表失败');
        }
      } catch (err) {
        console.error('获取班级列表失败:', err);
        message.error('获取班级列表失败，请刷新页面重试');
      } finally {
        setClassLoading(false);
      }
    };

    fetchClassList();
  }, []);

  const onFinish = async (values) => {
    try {
      const result = await dispatch(registerStudent({
        studentId: values.studentId,
        name: values.name,
        password: values.password,
        classId: values.classId
      })).unwrap();
      
      setRegisterSuccess(true);
      
      // 3秒后自动跳转到登录页面
      setTimeout(() => {
        navigate('/login');
      }, 3000);
    } catch (err) {
      // 错误已经在extraReducers中处理
    }
  };

  // 如果注册成功，显示成功结果页面
  if (registerSuccess) {
    return (
      <div className="register-container">
        <Card className="register-card">
          <Result
            status="success"
            title="注册成功！"
            subTitle="您的账号已创建成功，即将跳转到登录页面..."
            extra={[
              <Button 
                type="primary" 
                key="login" 
                onClick={() => navigate('/login')}
              >
                立即登录
              </Button>
            ]}
          />
        </Card>
      </div>
    );
  }

  return (
    <div className="register-container">
      <Card className="register-card" title="学生注册">
        <Spin spinning={loading}>
          {error && (
            <Alert
              message="注册失败"
              description={error}
              type="error"
              showIcon
              closable
              style={{ marginBottom: 24 }}
              onClose={() => dispatch(clearError())}
            />
          )}
          
          <Form
            form={form}
            name="register"
            onFinish={onFinish}
            autoComplete="off"
            size="large"
          >
            <Form.Item
              name="studentId"
              rules={[
                {
                  required: true,
                  message: '请输入学号！',
                },
                {
                  pattern: /^\d{8,12}$/,
                  message: '学号格式不正确，应为8-12位数字！',
                },
              ]}
            >
              <Input
                prefix={<IdcardOutlined />}
                placeholder="学号"
              />
            </Form.Item>

            <Form.Item
              name="name"
              rules={[
                {
                  required: true,
                  message: '请输入姓名！',
                },
                {
                  min: 2,
                  message: '姓名至少2个字符！',
                },
              ]}
            >
              <Input
                prefix={<UserOutlined />}
                placeholder="姓名"
              />
            </Form.Item>

            <Form.Item
              name="classId"
              rules={[
                {
                  required: true,
                  message: '请选择班级！',
                },
              ]}
            >
              <Select
                placeholder="请选择班级"
                loading={classLoading}
                prefix={<TeamOutlined />}
              >
                {classList.map(cls => (
                  <Option key={cls.id} value={cls.id}>{cls.name}</Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name="password"
              rules={[
                {
                  required: true,
                  message: '请输入密码！',
                },
                {
                  min: 6,
                  message: '密码至少6位！',
                },
              ]}
            >
              <Input.Password
                prefix={<LockOutlined />}
                placeholder="密码"
              />
            </Form.Item>

            <Form.Item
              name="confirmPassword"
              dependencies={['password']}
              rules={[
                {
                  required: true,
                  message: '请确认密码！',
                },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次输入的密码不一致！'));
                  },
                }),
              ]}
            >
              <Input.Password
                prefix={<LockOutlined />}
                placeholder="确认密码"
              />
            </Form.Item>

            <Form.Item>
              <Button 
                type="primary" 
                htmlType="submit" 
                className="register-button"
                loading={loading}
                block
              >
                注册
              </Button>
            </Form.Item>

            <div className="register-footer">
              已有账号？ <Link to="/login">立即登录</Link>
            </div>
          </Form>
        </Spin>
      </Card>
    </div>
  );
};

export default Register;